﻿using JustTest.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace JustTest.Admin
{
    public partial class BrowseUsers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public IQueryable<JustTest.Models.ApplicationUser> GridView_GetData()
        {
            JustTestDb context = new JustTestDb();

            return context.Users;
        }

        public void GridView_UpdateItem(string id)
        {
            JustTestDb contex = new JustTestDb();
            JustTest.Models.ApplicationUser user = contex.Users.Find(id);
            if (user == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }
            TryUpdateModel(user);
            if (ModelState.IsValid)
            {
                contex.SaveChanges();
            }
        }

        protected void ButtonToggleAuthor_Click(object sender, EventArgs e)
        {
            string userId = ((Button)sender).CommandArgument;
            JustTestDb context = new JustTestDb();
            JustTest.Models.ApplicationUser user = context.Users.FirstOrDefault(u=>u.Id == userId);

            var AuthorRole = user.Roles.FirstOrDefault(r => r.Role.Name == "Author");

            if (AuthorRole != null)
            {
                user.Roles.Remove(AuthorRole);
            }
            else
            {
                var dbAuthorRole = context.Roles.FirstOrDefault(r => r.Name == "Author");
                UserRole userRole = new UserRole{
                    Role = dbAuthorRole, User = user
                };
                user.Roles.Add(userRole);
            }

            context.SaveChanges();
            this.GridViewUsers.DataBind();
        }

    }
}